package al.jdbc.DAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import al.jdbc.dpbridge.DataSource;
import alOmrane.jdbc.beans.Type_contact;

public class TypeContactDAO {
	private Connection db;
	@SuppressWarnings("unused")
	private DataSource ds;
	private Statement sql;
	
	public TypeContactDAO(DataSource ds){
		db = ds.getConnection();
		this.ds = ds;
		try {
			sql = db.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public List<Type_contact> findAllTypeContactDAO(){
		List<Type_contact> org = new ArrayList<Type_contact>();
		try {
			String query = "SELECT * FROM type_contact";

			ResultSet rs = sql.executeQuery(query);
			while (rs.next()) {
				Type_contact o = new Type_contact();
				o.setId(Integer.parseInt(rs.getString(1)));
				o.setDesi_type_ctt(rs.getString(2));
				org.add(o);
			}
		}catch(Exception ex){
			return null;
		}
		return org;
	}
	
	public Type_contact findById(int id){
		try {
			String query = "SELECT * FROM type_contact" +
					" WHERE id_type_ctt="+id;

			ResultSet rs = sql.executeQuery(query);
			rs.next();
			Type_contact o = new Type_contact();
			o.setId(Integer.parseInt(rs.getString(1)));
			o.setDesi_type_ctt(rs.getString(2));
			return o;
		}catch(Exception ex){
			return null;
		}
	}
	
	public boolean insert(Type_contact o){
		try{

			StringBuffer sb = new StringBuffer("INSERT INTO type_contact VALUES " +
					"('"+o.getId()+"','"+o.getDesi_type_ctt()+"');");
			sql.executeUpdate(sb.toString());
			return true;
		}catch(Exception ex){
			ex.printStackTrace();
			return false;
		}
	}
	public boolean delete(Type_contact o){
		try{

			StringBuffer sb = new StringBuffer("DELETE FROM type_contact "+
					"WHERE id_type_ctt="+o.getId()+" ;");
			sql.executeUpdate(sb.toString());
			return true;
		}catch(Exception ex){
			System.out.println(ex.getMessage());
			return false;
		}
	}
	public int incrementEngine(){
		try {
			String query = "SELECT Max(id_type_ctt) FROM type_contact";

			ResultSet rs = sql.executeQuery(query);
			rs.next();
			return Integer.parseInt((rs.getString(1)==null)?"0":rs.getString(1))+1;
		}catch(Exception e){
			e.printStackTrace();
			return 0;
		}
	}
}
